import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useState } from 'react'
import { doLogin } from '@/api/system/login'
import { useIdentityStore } from '@/stores/identityStore'
import { produce } from 'immer'
import { useShallow } from 'zustand/react/shallow'

export const Route = createFileRoute('/login')({
    component: LoginPage,
})

function LoginPage() {
    const [loginForm, setLoginForm] = useState({ phone: '', password: '' })

    const changePhone = (event: React.ChangeEvent<HTMLInputElement>) => {
        const phoneValue = event.target.value
        setLoginForm(
            produce(draft => {
                draft.phone = phoneValue
            })
        )
    }

    const changePassword = (event: React.ChangeEvent<HTMLInputElement>) => {
        const passwordValue = event.target.value
        setLoginForm(
            produce(draft => {
                draft.password = passwordValue
            })
        )
    }

    const { setInfo } = useIdentityStore(
        useShallow(state => ({
            setInfo: state.setInfo,
        }))
    )
    const navigate = useNavigate()

    const handleLogin = () => {
        doLogin(loginForm).then(res => {
            if (res.code === 200) {
                const data = res.data
                setInfo(data)
                navigate({ to: '/' })
            }
        })
    }

    return (
        <div className="flex border-2 border-black h-screen justify-center items-center">
            <div className="w-400 h-400 border-2 border-black p-6">
                <input
                    value={loginForm.phone}
                    onChange={changePhone}
                    type="text"
                    placeholder="Phone"
                    className="w-full h-10 border-2 border-black p-2 mb-4"
                />
                <input
                    value={loginForm.password}
                    onChange={changePassword}
                    type="password"
                    placeholder="Password"
                    className="w-full h-10 border-2 border-black p-2 mb-4"
                />
                <button className="w-full h-10 border-2 border-black p-2 mb-4" onClick={handleLogin}>
                    Login
                </button>
            </div>
        </div>
    )
}
